//
//  UpdateVersion.m
//  LongriseHttpManageIOS
//
//  Created by 程三 on 17/5/16.
//  Copyright © 2017年 程三. All rights reserved.
//

#import "UpdateVersion.h"
#import "MBProgressHUD+PKX.h"

@implementation UpdateVersion

-(id)init
{
    self = [super init];
    if(self)
    {
        _methodName = @"lbcp_getAppVersion";
        _parameterName = @"appname";
        _mark = 1;//自动检测
        upgrade = 0;
    }
    return self;
}
-(void)checkVersion
{
    if(_mark == 0)
    {
        [MBProgressHUD showMessage:@"正在检查版本"];
    }
    
    if(!_baseURL  || !_methodName || !_parameterName || !_appName)
    {
        return;
    }
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:@"iOS_Village" forKey:@"appname"];
    [[AFNetWorkService2 getAFNetWorkService2] requestWithServiceIP2:UpdateURL ServiceName:@"" params:params httpMethod:@"POST" resultIsDictionary:YES completeBlock:^(id result, ResultType resultType) {
        if(_mark == 0)
        {
            [MBProgressHUD hideHUD];
        }
        if(result != nil)
        {
            NSDictionary *tempDic = (NSDictionary *)result;
            if(tempDic)
            {
                float serverVersionNum = -1;
                //获取服务器版本
                NSString *serverVersion = result[@"appversion"];
                serverVersionNum = (serverVersion == nil ? -1 : [serverVersion floatValue]);
                
                upgrade = [result objectForKey:@"upgrade"];
                
                //获取下载地址
                //                downURL = [NSString stringWithFormat:@"itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=%d",myAppID];;
                
                //判断是非升级
                if(_currentVersion < serverVersionNum)
                {
                    NSArray *arys = [result[@"remarks"] componentsSeparatedByString:@"。"];
                    NSString *remarksStr = [self decompositionAry:arys];
                    if (self.updateBlock) {
                        if([@"1" isEqualToString:upgrade])    //强制升级
                        {
                            self.updateBlock(YES,YES, remarksStr);
                        }
                        else {
                            self.updateBlock(YES,NO, remarksStr);
                        }
                    }
                }
            }
        }
    }];
}

- (NSString *)decompositionAry:(NSArray *)array
{
    NSString *string = nil;
    NSString *str = nil;
    for (int i = 0; i < array.count; i++) {
        if (i == 0) {
            str = array[i];
            string = [NSString stringWithFormat:@"%@\n",str];
        }
        else if (i < array.count - 1 && i > 0) {
            str = array[i];
            string = [NSString stringWithFormat:@"%@%@\n",string,str];
        }
        else {
            str = array[i];
            string = [NSString stringWithFormat:@"%@%@",string,str];
        }
    }
    
    return string;
}

@end

